///@file ClosedPolyline.cpp
///@brief Implementation of the class representing a closed polyline
///@author Arnaud Duval
///@version 0.0
///@date 2010/03/31

#include "../include/ClosedPolyline.h"
#include <cassert>
#include <fstream>

///@brief Default constructor
ClosedPolyline::ClosedPolyline()
{
	nbpts = 0;
}

///@brief Constructor from a file
///@param file Path to the file to read, containing a list of X, Y points
ClosedPolyline::ClosedPolyline(std::string file)
{
	nbpts = 0;
	std::ifstream fin(file.c_str());
	while(true)
	{
		Point temp(2);
		double x,y;
		fin >> x >> y;
		if (!fin.eof())
		{
			temp.Coord(1) = x;
			temp.Coord(2) = y;
			AddPoint(temp);
		}
		else
			break;
	}
}

///@brief Copy constructor
///@param p ClosedPolyline object to copy
ClosedPolyline::ClosedPolyline(const ClosedPolyline& p)
{
	nbpts = p.nbpts;
	points = new Point[nbpts];
	for(unsigned int i = 0 ; i < nbpts ; i++)
	{
		points[i] = p.points[i];
	}
}

///@brief Desctructor
ClosedPolyline::~ClosedPolyline()
{
	if(nbpts != 0)
		delete[] points;
}

///@brief Add a point to polyline
///@param p Point to add at the end of the polyline
void ClosedPolyline::AddPoint(Point p)
{
	if(nbpts != 0)
	{
		Point* temp = new Point[nbpts];
		for(unsigned int i = 0 ; i < nbpts  ; i++)
		{
			temp[i] = points[i];
		}
		delete[] points;
		nbpts++;
		points = new Point[nbpts];
		for(unsigned int i = 0 ; i < nbpts-1 ; i++)
		{
			points[i] = temp[i];
		}
		delete[] temp;
	}
	else
	{
		nbpts++;
		points = new Point[nbpts];
	}
	points[nbpts-1] = p;
}

///@brief Test if a point is located inside polyline
///@bug Not implemented yet
bool ClosedPolyline::IsInPolyline(Point)
{
	return false;
}

///@brief Return number of points
unsigned int ClosedPolyline::Nbpts()
{
	return nbpts;
}

///@brief Overload of [] operator : direct access to a given point
///@param i index of returned Point
Point& ClosedPolyline::operator[](unsigned int i) const
{
	assert((i >=1)&&(i <= nbpts));
	return points[i-1];
}



